package com.zhuqian.myapplication

import android.content.Context
import android.graphics.BitmapFactory
import android.os.Handler
import android.os.Looper
import android.os.Message
import kotlin.math.abs

object ThreadUtils {
    var fn: (() -> Unit)? = null
    val handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            fn?.invoke()
        }
    }

    fun runOnMainThread(fn: () -> Unit) {
        ThreadUtils.fn = fn
        handler.sendEmptyMessage(1)
    }
}


data class Params(val conf: Float, val iou: Float, var mean: Float = 0.0f, var std: Float = 0.0f)

fun range(start:Float, end:Float, step:Float): List<Float>{
    val res = ArrayList<Float>()
    var i = start
    while (i < end){
        res.add(i)
        i += step
    }
    return res
}

fun search_params(context: Context, detector: Detector){
    // 获取assets下所有jpg结尾的图片
    val paths = context.assets.list("")!!.filter { it.endsWith(".jpg") }

    val Params = ArrayList<Params>()
    val confs = range(0.25f, 0.35f, 0.02f)
    val ious = range(0.25f, 0.35f, 0.02f)
    for (conf in confs){
        for (iou in ious){
            Params.add(Params(conf, iou))
        }
    }
    var min_mean_params: Params? = Params(0.0f, 0.0f, 1000.0f, 0.0f)
    var min_std_params: Params? = Params(0.0f, 0.0f, 0.0f, 1000f)

    for (pm in Params){
        detector.conf = pm.conf
        detector.iou = pm.iou
        val ret = ArrayList<Float>()
        for (path in paths){
            val bitmap = BitmapFactory.decodeStream(context.assets.open(path))
            val results = detector.detect_bitmap(bitmap)
            val predict_n = results.size
            val true_n = path.split(".")[0].split("_")[1].toInt()
            ret.add(abs(predict_n - true_n).toFloat())
        }
        val mean = ret.sum() / ret.size
        val std = ret.map { (it - mean) * (it - mean) }.sum() / ret.size
        pm.mean = mean
        pm.std = std
        min_mean_params = if (mean < min_mean_params!!.mean) pm else min_mean_params
        min_std_params = if (std < min_std_params!!.std) pm else min_std_params
        println("参数搜索结果" + pm.toString())
    }
    println("最小均值参数" + min_mean_params.toString())
    println("最小方差参数" + min_std_params.toString())
}